<?php 
/*
 module:		礼物记录
 create_time:	2022-03-07 18:03:51
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\service\ZhGiveGiftService;
use app\api\model\ZhGiveGift as ZhGiveGiftModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\api\model\Gift as GiftModel;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\backend\model\ZhGiftOrder as ZhGiftOrderModel;
use app\api\model\ZhPayLog as ZhPayLogModel;
use app\api\service\PaymentService;
use app\api\model\ZhBalanceLog as ZhBalanceLogModel;
use utils\wechart\TemplateService;

class ZhGiveGift extends Common {


	/**
	* @api {get} /ZhGiveGift/index 01、首页数据列表
	* @apiGroup ZhGiveGift
	* @apiVersion 1.0.0
	* @apiDescription  首页数据列表

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"

	* @apiParam (输入参数：) {int}     		[limit] 每页数据条数（默认20）
	* @apiParam (输入参数：) {int}     		[page] 当前页码

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码 201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.data 返回数据
	* @apiParam (成功返回参数：) {string}     	array.data.list 返回数据列表
	* @apiParam (成功返回参数：) {string}     	array.data.count 返回数据总数
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":""}
	* @apiErrorExample {json} 02 失败示例
	* {"status":" 201","msg":"查询失败"}
	*/
	function index(){
        $wxapp_id     = $this->request->get('wxapp_id');
        $uId          = $this->request->uid;
        $type         = $this->request->get('type','','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting    = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
		$limit  = $this->request->get('limit', 20, 'intval');
		$page   = $this->request->get('page', 1, 'intval');
		$where = [];
		$where['wxapp_id'] = $wxapp_id;
		
        if($type == 0){
            $where['user_id']      = $uId;
        }elseif ($type == 1){
            $where['give_user_id'] = $uId;
        }
		
		$field   = '*';
		$orderby = 'id desc';

		$res = ZhGiveGiftService::indexList(formatWhere($where),$field,$orderby,$limit,$page);
//		dd($res);die;
        $tobal = ZhGiveGiftModel::where($where)->field('SUM(num) as giftNum,SUM(total_price) as giftPrice')->find()->toArray();
        $res['total_price'] = $tobal['giftPrice'] ? $tobal['giftPrice'] : 0;
        $res['total_num']   = $tobal['giftNum'] ? $tobal['giftNum'] : 0;
		foreach ($res['list'] as &$v){
            $giveUserData = MemberModel::where([
                                        'uid'     => $v['give_user_id'],
                                        'wxapp_id' => $wxapp_id])->value('real_name');
            $v['give_nickname'] = $giveUserData;
            $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            $GiftData        = GiftModel::where([
                                                'wxapp_id'=> $wxapp_id,
                                                'id'=>$v['give_id'],
                                                'status'=>1])
                                        ->find();
//            $v['gift_image'] = $this->request->domain() . $GiftData['image'];
            $v['gift_image'] = $GiftData['image'];
        }
		unset($v);
		return $this->ajaxReturn($this->successCode,'返回成功',htmlOutList($res));
	}
	
	/**赠送礼物**/
    function giveGift(){
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $giftId   = $this->request->post('gift_id','','serach_in');// 礼物id
        $num      = $this->request->post('gift_num','','serach_in');
        $sid      = $this->request->post('s_id','','serach_in');
        $sName    = $this->request->post('s_name','','serach_in');
        $type     = $this->request->post('type','','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting    = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
    
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        if(!$giftId){
            return $this->ajaxReturn($this->errorCode,'缺少信息参数');
        }
        $giftData = GiftModel::where(['wxapp_id'=> $wxapp_id,'id'=> $giftId])->find();
        if(!$giftData){
            return $this->ajaxReturn($this->errorCode,'信息参数错误');
        }
        if(!$sid){
            return $this->ajaxReturn($this->errorCode,'缺少信息参数接收者id');
        }
        if(!$sName){
            return $this->ajaxReturn($this->errorCode,'缺少信息参数接收者姓名');
        }
        if(!$num){
            return $this->ajaxReturn($this->errorCode,'缺少信息参数数量');
        }
        // 后台判断用户红心是否足够
        if($user['virtual_currency_balance'] < $giftData['price']){
            return $this->ajaxReturn($this->errorCode,'您的红心不足，请先前往充值');
        }
        $totalPrice = round($num * $giftData['price']);
        
        // type 1|赠送 0|购买 应该改流程与逻辑了，type闲置，都赋值1
        $ZhGiveGiftId = ZhGiveGiftModel::insertGetId([
                                        'wxapp_id'    => $wxapp_id,
                                        'name'        => $giftData['name'],
                                        'price'       => $giftData['price'],
                                        'num'         => $num,
                                        'total_price' => $totalPrice,
                                        'user_id'     => $sid,
                                        'give_user_id'=> $uId,
                                        'createtime'  => time(),
                                        'user_name'   => $sName,
                                        'give_id'     => $giftId,
                                        'type'        => 1
                                    ]);
        if($ZhGiveGiftId){
            // 修改我的红心余额
            $myLiBBalance = round($user['virtual_currency_balance'] - $totalPrice);
            $r            = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])
                                       ->update(['virtual_currency_balance'=> $myLiBBalance]);
            if($r){
                // 查询收礼物人的余额（不是红心余额）
                $SUser       = MemberModel::where(['uid' => $sid, 'wxapp_id' => $wxapp_id])->find();
                $sLiBBalance = $SUser['balance'] ? $SUser['balance'] : 0;
                
                // 红心转人民币比例
                $bili        = round(1/$wxSetting['proportion'],2);
                
                // 红心转为金额
                $tPrice      = round($totalPrice * $bili,2);
                
                $pId         = 0;
                $chouChengPrice = 0;
                // 分销给红娘
                if(!$SUser['p_id'] && $SUser['matchmaker_id']){
                    $chouChengB     = round($wxSetting['matchmaker_take_prop'] / 100,2);
                    $chouChengPrice = round($tPrice * $chouChengB,2);
                    $pId            = $SUser['matchmaker_id'];
                }
                // 如果有红娘走这里
                if($pId){
                    $Puser       = MemberModel::where(['uid' => $pId, 'wxapp_id' => $wxapp_id])->find();
                    $pYuE        = $Puser['balance'] ? $Puser['balance'] : 0;
                    $PNewBalance = round($pYuE + $chouChengPrice,2);
                    MemberModel::where(['uid' => $pId, 'wxapp_id' => $wxapp_id])
                               ->update(['balance'=> $PNewBalance]);
                    ZhBalanceLogModel::insert([
                        'u_id'         => $pId,
                        'wxapp_id'     => $wxapp_id,
                        'start_balance'=> $pYuE,
                        'end_balance'  => $PNewBalance,
                        'type'         => '收入',
                        'remake'       => '礼物收益',
                        'create_time'  => time(),
                        'num'          => $chouChengPrice
                    ]);
                }
                // 最后改收礼物人的余额
                $SNewLiBBalance = round($sLiBBalance + ($tPrice - $chouChengPrice),2);
                $res            = MemberModel::where(['uid' => $sid, 'wxapp_id' => $wxapp_id])->update(['balance'=> $SNewLiBBalance]);
                ZhBalanceLogModel::insert([
                    'u_id'         => $sid,
                    'wxapp_id'     => $wxapp_id,
                    'start_balance'=> $sLiBBalance,
                    'end_balance'  => $SNewLiBBalance,
                    'type'         => '收入',
                    'remake'       => ($user['real_name'] ? $user['real_name'] : $user['nickname']) . '赠送礼物' . $giftData['name'] . $num . '朵，价值红心' . $giftData['price'],
                    'create_time'  => time(),
                    'num'          => round($tPrice - $chouChengPrice,2)
                ]);
                $TemplateService = new TemplateService();
                $sUserData = MemberModel::where(['uid' => $sid, 'wxapp_id' => $wxapp_id])
                                             ->find();
               
                if($sUserData && $type == 'wx'){
                    $moban = [
                        'thing1' => [
                            'value' => $sUserData['nickname'],
                        ],
                        'time2' => [
                            'value' => date('Y-m-d H:i:s',time()),
                        ],
                        'thing3' => [
                            'value' => $user['nickname'] . '赠送了一个你礼物，进入小程序查看详情',
                        ],
                    ];
                    $a =  $TemplateService->sendSubscribeMessage(['wxapp_id'=> $wxapp_id,'openid'=> $sUserData['openid'],'template_id'=> $wxSetting['gift_template_id'],'data'=> $moban]);
                    
                }
                
            }
        }
        return $this->ajaxReturn($this->successCode,'返回成功',$res);
    }
	
	/**购买礼物----闲置**/
    function addGiveGift(){
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $wxSetting    = SysSiteModel::where('wxapp_id',$wxapp_id)->find();
        if(!$wxSetting){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
    
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        
    }


}

